<template>
  <a-modal
    :title="title"
    :width="800"
    :ok=false
    :visible="visible"
    :confirmLoading="confirmLoading"
    :okButtonProps="{ props: {disabled: disableSubmit} }"
    @ok="handleOk"
    @cancel="handleCancel">

    <a-spin :spinning="confirmLoading">
      <a-form :form="form">

        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          :label="$t('systemManagement.departName')"
          :hidden="false"
          hasFeedback >
          <a-input id="departName" :placeholder="$t('base.pleaseEnter')" v-decorator="['departName', validatorRules.departName ]"/>
        </a-form-item>

        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :hidden="seen" :label="$t('systemManagement.superiorDepart')" hasFeedback>
        <a-tree-select
          style="width:100%"
          :dropdownStyle="{maxHeight:'200px',overflow:'auto'}"
          :treeData="departTree"
          v-model="model.parentId"
          :placeholder="$t('base.pleaseChoose')"
          :disabled="condition">
        </a-tree-select>
        </a-form-item>

        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          :label="$t('systemManagement.orgCategory')">
          <template v-if="seen">
          <a-radio-group v-decorator="['orgCategory',validatorRules.orgCategory]" :placeholder="$t('base.pleaseChoose')">
            <a-radio value="1">
              {{$t('systemManagement.company')}}
            </a-radio>
          </a-radio-group>
          </template>
          <template v-else>
            <a-radio-group v-decorator="['orgCategory',validatorRules.orgCategory]" :placeholder="$t('base.pleaseChoose')">
              <a-radio value="2">
                {{$t('systemManagement.department')}}
              </a-radio>
              <a-radio value="3">
                {{$t('systemManagement.post')}}
              </a-radio>
            </a-radio-group>
          </template>
        </a-form-item>

        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          :label="$t('light.phoneNumber')">
          <a-input :placeholder="$t('base.pleaseEnter')" v-decorator="['mobile',validatorRules.mobile]" />
        </a-form-item>
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          :label=" $t('systemManagement.fax') ">
          <a-input :placeholder="$t('base.pleaseEnter')" v-decorator="['fax', {}]"  />
        </a-form-item>
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          :label="$t('systemManagement.address')">
          <a-input :placeholder="$t('base.pleaseEnter')" v-decorator="['address', {}]"  />
        </a-form-item>
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          :label="$t('systemManagement.sort')">
          <a-input-number v-decorator="[ 'departOrder',{'initialValue':0}]" />
        </a-form-item>

        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          :label="$t('base.memo')">
          <a-textarea :placeholder="$t('base.pleaseEnter')" v-decorator="['memo', {}]"  />
        </a-form-item>

        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          :label="$t('systemManagement.platFormLogo')">
          <a-upload
            name="file"
            v-decorator="['file', {}]"
            :action="uploadAction"
            :headers="headers"
            :fileList="fileList"
            :multiple="false"
            @change="handleChange"
            accept=".jpg,.gif,.png,.jpeg"
            :beforeUpload="beforeUpload"
          >

            <a-button> <a-icon type="upload" /> {{$t('systemManagement.uploadPlatformLogo')}} </a-button>
            <div>
              {{$t('systemManagement.pictureResolutionInfo')}}
            </div>

          </a-upload>
        </a-form-item>

        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          :label=" $t('systemManagement.platFormTitleEn') ">

          <a-input :placeholder="$t('base.pleaseEnter')" v-decorator="['platFormTitleEn', {}]" />
        </a-form-item>

        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          :label=" $t('systemManagement.platFormTitleCn') ">
          <a-input :placeholder="$t('base.pleaseEnter')" v-decorator="['platFormTitleCn', {}]" />
        </a-form-item>

        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          :label=" $t('systemManagement.platFormCopyRightName') ">
          <a-input :placeholder="$t('base.pleaseEnter')" v-decorator="['platFormCopyRightName', {}]" />
        </a-form-item>

        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          :label=" $t('systemManagement.platFormCopyRightUrl') ">
          <a-input :placeholder="$t('base.pleaseEnter')" v-decorator="['platFormCopyRightUrl', {}]" />

        </a-form-item>

      </a-form>
    </a-spin>
  </a-modal>
</template>

<script>
  import { httpAction } from '@/api/manage'
  import { queryIdTree } from '@/api/api'
  import pick from 'lodash.pick'
  import ATextarea from 'ant-design-vue/es/input/TextArea'
  import {ACCESS_TOKEN} from "@/store/mutation-types"
  import { getUploadFileList,getFilePaths } from '@/utils/commonUploadFile.js'
  import Vue from 'vue'

  export default {
    name: "SysDepartModal",
    components: { ATextarea },
    data () {
      return {
        headers: {},
        fileList: [],
        departTree:[],
        orgTypeData:[],
        phoneWarning:'',
        departName:"",
        title:this.$t('base.operation'),
        seen:false,
        visible: false,
        condition:true,
        disableSubmit:false,
        model: {},
        menuhidden:false,
        menuusing:true,
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },

        confirmLoading: false,
        form: this.$form.createForm(this),
        validatorRules:{
        departName:{rules: [{ required: true, message: this.$t('base.pleaseEnter')+'!' }]},
        orgCode:{rules: [{ required: true, message: this.$t('base.pleaseEnter')+'!' }]},
         mobile:{rules: [{validator:this.validateMobile}]}
        },
        url: {
          add: "/sys/sysDepart/add",
          fileUpload: window._CONFIG['domianURL']+"/glr/glrResource/platFormLogoUpload",
        },
        dictDisabled:true,
      }
    },
    created () {
      const token = Vue.ls.get(ACCESS_TOKEN);
      this.headers = {"X-Access-Token": token};
    },
    computed:{
      uploadAction:function () {
        return this.url.fileUpload;
      }
    },
    methods: {
      loadTreeData(){
        var that = this;
        queryIdTree().then((res)=>{
          if(res.success){
            that.departTree = [];
            for (let i = 0; i < res.result.length; i++) {
              let temp = res.result[i];
              that.departTree.push(temp);
            }
          }
        })
        this.model.filePath="";
        this.fileList=[];
      },
      add (depart) {
        if(depart){
          this.seen = false;
          this.dictDisabled = false;
        }else{
          this.seen = true;
          this.dictDisabled = true;
        }
        this.edit(depart);
      },
      edit (record) {
          this.form.resetFields();
          this.model = Object.assign({}, {});
          this.visible = true;

          this.model.filePath="";
          this.fileList=[];

          let currFileList = getUploadFileList(this.model.filePath);
          console.info(currFileList);
          this.fileList = [...currFileList]

          this.loadTreeData();
          this.model.parentId = record!=null?record.toString():null;
          if(this.seen){
            this.model.orgCategory = '1';
          }else{
            this.model.orgCategory = '2';
          }
          this.$nextTick(() => {
            this.form.setFieldsValue(pick(this.model,'orgCategory','departName','departNameEn','departNameAbbr','departOrder','description','platFormLogo','platFormTitleEn','platFormTitleCn',
              'platFormCopyRightName','platFormCopyRightUrl',
                'orgType','orgCode','mobile','fax','address','memo','status','delFlag'))
          });
      },
      close () {
        this.$emit('close');
        this.disableSubmit = false;
        this.visible = false;
      },
      handleOk () {
        const that = this;

        if (that.fileList.length==0){
          //that.$message.warning("没有上传的文件");
          //return;
        }else {
          if ("done"==that.fileList[0].status){

          }else {
            that.$message.warning( that.$t('systemManagement.fileUploadeding') );
            return;
          }
        }
        if (that.fileList.length==1||that.fileList.length==0){

        }else {
          that.$message.warning( that.$t('systemManagement.onlyOneFileUploaded') );
          return;
        }

        // 触发表单验证
        this.form.validateFields((err, values) => {
          if (!err) {
            that.confirmLoading = true;
            let formData = Object.assign(this.model, values);
            formData.filePath = getFilePaths(this.fileList);
            //时间格式化
            console.log(formData)
            httpAction(this.url.add,formData,"post").then((res)=>{
              if(res.success){
                that.$message.success(res.message);
                that.loadTreeData();
                that.$emit('ok');
              }else{
                that.$message.warning(res.message);
              }
            }).finally(() => {
              that.confirmLoading = false;
              that.close();
            })

          }
        })
      },
      handleCancel () {
        this.close()
      },

      handleChange(info) {
        if (info.file.status === 'uploading') {
          this.fileList = info.fileList;
          return
        }
        if (info.file.status === 'removed') {
          this.fileList=info.fileList;
          return
        }
        if (info.file.status === 'done') {
          this.fileList = info.fileList;
          var response = info.file.response;
          if (!response.success) {
            this.$message.warning(response.message);
          }
        }
      },
      beforeUpload(file) {
        if (this.fileList.length>0){
          this.$message.error( this.$t('systemManagement.onlyOneFileUploaded') );
          return false;
        }
        var isJPG=false;
        var fileType=file.type.toLowerCase();
       if(fileType.indexOf('png')!=-1){
          isJPG=true;
        }
        if(!isJPG){
          this.$message.error( this.$t('systemManagement.onlyFilesPNGFormat') );
          this.fileList=[];
          return false;
        }
        var isLt2M = true;
        if ((file.size / 1024)>15) {
          this.$message.error( this.$t('systemManagement.maximumSize') );
          this.fileList=[];
          return false;
        }
        if(isJPG && isLt2M){
          return true;
        }
      },

      validateMobile(rule,value,callback){
        if (!value || new RegExp(/^1([38][0-9]|4[579]|5[0-3,5-9]|6[6]|7[0135678]|9[89])\d{8}$/).test(value)){
          callback();
        }else{
          callback( this.$t('systemManagement.enterCorrectPhoneNumber') );
        }
      },

    }
  }
</script>

<style scoped>

</style>